34C - Page Numbers - CodeForces Solution


expression parsing implementation sortings strings *1300

Please click on ads to support us..

Python Code:

s = sorted(list(set(map(int, input().split(',')))))
i = 0
ans = ""
while i < len(s):
    ans += f"{s[i]}"
    beg = i
    while i < len(s) - 1 and s[i] == s[i + 1] - 1:
        i += 1
    if beg == i:
        ans += ","
    else:
        ans += f"-{s[i]},"
    i += 1
ans = ans.strip(',')
print(ans)

C++ Code:

#include <iostream>
#include <vector>

std::vector<int> parseString(std::string s){

    int x(0);
    std::vector<int> nums;
    for(long p = 0; p < s.size(); p++){
        if(s[p] == ','){nums.push_back(x); x = 0;}
        else{x = 10 * x + (s[p] - '0');}
    }
    nums.push_back(x);
    return nums;
}

int main(){

    const long N = 1111;
    std::ios_base::sync_with_stdio(false);
    std::string s; std::cin >> s;
    std::vector<int> nums = parseString(s);
    std::vector<bool> a(N, 0);
    for(long p = 0; p < nums.size(); p++){a[nums[p]] = true;}

    long from(-1), initial(1);
    for(long p = 0; p < N; p++){
        if(!a[p]){
            if(from >= 0){
                long to = p - 1;
                if(!initial){std::cout << ",";}
                initial = false;
                if(from < to){std::cout << from << "-" << to;}
                else{std::cout << from;}
            }
            from = -1;
        }
        else if(a[p] && from < 0){from = p;}
    }

    std::cout << std::endl;

    return 0;
}


Comments

Submit
0 Comments
More Questions

896A - Nephren gives a riddle
761A - Dasha and Stairs
1728B - Best Permutation
1728A - Colored Balls Revisited
276B - Little Girl and Game
1181A - Chunga-Changa
1728C - Digital Logarithm
1728D - Letter Picking
792B - Counting-out Rhyme
1195A - Drinks Choosing
5D - Follow Traffic Rules
1272A - Three Friends
1632D - New Year Concert
1400D - Zigzags
716C - Plus and Square Root
412A - Poster
844B - Rectangles
1591A - Life of a Flower
1398C - Good Subarrays
629A - Far Relative’s Birthday Cake
1166A - Silent Classroom
1000B - Light It Up
218B - Airport
1463B - Find The Array
1538C - Number of Pairs
621B - Wet Shark and Bishops
476B - Dreamoon and WiFi
152C - Pocket Book
1681D - Required Length
1725D - Deducing Sortability